import re
import ast


def reg_search(text, regex_list):

    results = []

    for regex_item in regex_list:
        result_item = {}

        for field, pattern in regex_item.items():
            matches = re.findall(pattern, text)

            if matches:
                if len(matches) == 1 and isinstance(matches[0], str):
                    result_item[field] = matches[0]
                elif len(matches) == 1 and isinstance(matches[0], tuple):
                    result_item[field] = matches[0][0] if matches[0] else None
                else:
                    processed_matches = []
                    for match in matches:
                        if isinstance(match, tuple):
                            processed_matches.extend(list(match))
                        else:
                            processed_matches.append(match)
                    result_item[field] = processed_matches

        if result_item:
            results.append(result_item)

    return results


def main():

    print("请输入需要匹配的文本内容（输入完毕后，单独输入一行'EOF'结束）：")
    text_lines = []
    while True:
        line = input()
        if line.strip().upper() == 'EOF':
            break
        text_lines.append(line)
    text = '\n'.join(text_lines)

    # 接收用户输入的正则表达式列表
    print("\n请输入正则表达式列表（使用Python字典格式，例如：[{\"key1\": \"pattern1\", \"key2\": \"pattern2\"}]）：")
    while True:
        try:
            regex_input = input()
            regex_list = ast.literal_eval(regex_input)

            # 验证输入格式是否正确
            if isinstance(regex_list, list) and all(isinstance(item, dict) for item in regex_list):
                break
            else:
                print("输入格式不正确，请确保输入的是字典列表")
        except (SyntaxError, ValueError):
            print("输入格式有误，请重新输入正确的Python字典列表格式")

    # 执行匹配并输出结果
    print("\n匹配结果：")
    results = reg_search(text, regex_list)
    print(results)


if __name__ == "__main__":
    main()
